//   Copyright 2010 Shantanu Shah<shantanus@gmail.com>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.shansense.changemodetimer;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;

import com.shansense.coretimer.ChangeModeUtil;

/**
 * BroadcastReceiver for listening to ringer mode changes.
 * @author Shantanu Shah <shantanus@gmail.com>
 */
public class SilenceModeBroadcastReceiver extends BroadcastReceiver {
  
  @Override
  public void onReceive(Context context, Intent intent) {
    int currentRingerMode = intent.getIntExtra(android.media.AudioManager.EXTRA_RINGER_MODE, -1);
    if ((currentRingerMode != AudioManager.RINGER_MODE_SILENT)  &&
        (currentRingerMode != AudioManager.RINGER_MODE_VIBRATE)) return;
    
    SharedPreferences settings = context.getSharedPreferences(SilenceModeUtil.getAppName(),
        Context.MODE_PRIVATE);
    final long disabledTimeMillis = settings.getLong(ChangeModeUtil.DISABLED_TIME_MS, 0);
    if(disabledTimeMillis + (1000 * 5) > System.currentTimeMillis()) {
      return;
    }
    Intent newActivityIntent = new Intent();
    newActivityIntent.setAction(Intent.ACTION_MAIN);
    newActivityIntent.setClassName(context, SilenceModeUtil.packageName + ".SilenceModeTimer");
    newActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // If our app is already on top, don't create a new one.
    // This is important because as soon as you put your phone in silence mode,
    // this receiver will receive an intent, and we don't want to start a new activity again.
    newActivityIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(newActivityIntent);
  }

  public static ComponentName componentName() {
    return new ComponentName(SilenceModeUtil.packageName,
        SilenceModeUtil.packageName + ".SilenceModeBroadcastReceiver");
  }
}
